package gqz.mvvm.view;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;

import gqz.mvvm.R;
import gqz.mvvm.databinding.ActivityMainBinding;
import gqz.mvvm.model.Account;
import gqz.mvvm.viewmodel.MainVm;

public class LoginActivity extends BaseActivity implements MainIF, View.OnClickListener {

    String TAG = "MainActivity---";

    private ActivityMainBinding binding;
    private MainVm mainVm;

    private boolean checkState = false;//验证码校对状态

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        mainVm = new MainVm(this);

        binding.mainBtnLogin.setOnClickListener(this);
        binding.mainTvCode.setOnClickListener(this);

        binding.mainEtCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                mainVm.checkCode(s.toString());
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_btn_login:
                Log.d(TAG, "onClick: ");
//                startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                mainVm.login(binding.mainEtName.getText().toString(), binding.mainEtPwd.getText().toString(), checkState);
                break;
            case R.id.main_tv_code:
                mainVm.createCheckCode();
                break;
        }
    }

    @Override
    public void bindAccount(Account account) {
        binding.setAccount(account);
    }

    @Override
    public void refreshCheckCode(String code) {
        binding.mainTvCode.setText(code);
        if (mainVm != null)
            mainVm.checkCode(binding.mainEtCode.getText().toString());
    }

    @Override
    public void refreshCheckCodeIcon(boolean right) {
        if (right) {
            binding.mainIvCode.setBackground(getResources().getDrawable(R.mipmap.icon_true));
            checkState = true;
        } else {
            binding.mainIvCode.setBackground(getResources().getDrawable(R.mipmap.icon_false));
            checkState = false;
        }
    }

    @Override
    public void loginSuccess() {
        toast("登录成功");
//        startActivity(new Intent(LoginActivity.this, HomeActivity.class));
    }

    @Override
    public void loginFailed() {
        toast("登录失败");
    }
}
